import { ref , reactive} from 'vue'
function useMedia(props){
  if(Object.prototype.toString.call(props) === '[object Object]'){
    const mediaRecorder = ref(null)
    const thunks = reactive([])
    const blob = ref(null)
    const stream = ref(null)
    const start = () => {
       navigator.mediaDevices.getUserMedia(props).then((res)=>{
        console.log(res);
        stream.value = res
        mediaRecorder.value = new MediaRecorder(res)
        if(mediaRecorder.value){
          mediaRecorder.value.ondataavailable = (e) => {
            thunks.push(e.data)
          }
          mediaRecorder.value.onstop = () =>{
             blob.value = new Blob(thunks,{type: props.video ?
             'video/mp4' : 'audio/mp3'})
          }
          mediaRecorder.value.start()
        }
        
       })
    }
    const end = () => {
      mediaRecorder.value.stop()
      stream.value.getTracks().forEach((track) =>{
        track.stop()
      })
      thunks.length = 0
    }
    return [blob,start,end]
  }else {
    return [null,null,null]
  }
  
}
export default useMedia